package cn.max.services;

import cn.incontent.cda.client.common.ArgumentList;
import cn.incontent.fastjson.JSONArray;
import cn.incontent.fastjson.JSONObject;
import cn.max.controllers.ADService;
import cn.max.plat.db.DBManager;
import cn.max.plat.db.DBUtils;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import org.apache.cxf.common.util.StringUtils;

import java.text.SimpleDateFormat;

/**
 * Created by Max-Goday on 15/7/27.
 */
public class ClusterService extends ADService{

	public static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public void addClusterServerInfo() {

		ArgumentList args = getArgs();

		if (StringUtils.isEmpty(args.get("server_ssh_port"))) {
			args.add("server_ssh_port", "22");
		}

		BasicDBObject server = new BasicDBObject("name", args.get("server_name"))
				.append("ip", args.get("server_ip"))
				.append("port", args.get("server_ssh_port"))
				.append("login_name", args.get("server_login_id"))
				.append("login_password", args.get("server_login_password"))
				.append("deploy_dir", args.get("app_deploy_dir"))
				.append("des", args.get("server_des"))
				.append("repo_name", args.get("repo_name"))
				.append("last_deployment_revision", "")
				.append("last_deployment_at", "");

		DBManager.getClusterRepo().insert(server);

		out(getMsg(true, ""));

	}

	public void getClusterByRepo() {

		ArgumentList args = getArgs();
		JSONObject result = new JSONObject();

		String Git_Name = args.get("repo");

		int current, rowCount;

		try {
			current = Integer.parseInt(args.get("current"));
			rowCount = Integer.parseInt(args.get("rowCount"));
		} catch (Exception e) {
			current = 1;
			rowCount = 15;
		}

		int _skip_line_count = (current - 1) * rowCount;

		result.put("current", current);
		result.put("rowCount", rowCount);

		JSONArray arr = new JSONArray();

		int total = 0;

		try {

			DBCursor cursor = DBUtils.getClusterServersByRepo(Git_Name);

			while (cursor.hasNext()) {

				total ++;
				if (total <= _skip_line_count) continue;

				JSONObject item = new JSONObject();

				DBObject server = cursor.next();

				item.put("Name", server.get("name"));
				item.put("Last Deployment Revision", server.get("last_deployment_revision"));
				item.put("Last Deployment At", server.get("last_deployment_at"));
				item.put("IP", server.get("ip"));
				item.put("PORT", server.get("port"));
				item.put("Deploy Dir", server.get("deploy_dir"));

				arr.add(item);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		result.put("success", true);
		result.put("total", total);
		result.put("rows", arr);

		out(result);

	}

}
